package fr.jhaccoun.demenager_eco.web.utilisateur.connexion;

import javax.servlet.ServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; 
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import fr.jhaccoun.demenager_eco.utilisateur.UtilisateurService;

 
//TODO test des controllers

@Controller
public class LoginController {

	private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);
	
	@Autowired 
	private UtilisateurService userService;
	
	@RequestMapping(value = "/connexion", method = RequestMethod.GET)
	public String initLoginPage(Model model) { 
		LOGGER.info("Initialisation du form login");
		
		if(userService.isLogged()){
			return "redirect:/";
		}
		model.addAttribute("loginForm",new LoginForm());
		return "front.login.login";
	}
	 
	@RequestMapping(value="/connexion", method = RequestMethod.POST)
	public String login(@Valid @ModelAttribute("loginForm") LoginForm loginForm, BindingResult bresult,
			ServletRequest request) {
 
		LOGGER.info("Validation du form login {}",loginForm);
		
		if (bresult.hasErrors()) {
			return "front.login.login";
		} 
		return "forward:/login-management";
	}
	

	@RequestMapping(value="/connexion-echec")
	public String loginError(Model model) { 
		model.addAttribute("error", "true");
		return "front.login.login"; 
	}
	
	
}
